package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/6/20 20:40
 * @desciption
 */
@Service
@Slf4j
public class ISearchServiceImpl implements ISearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) throws IOException {
        SearchRequest searchRequest = new SearchRequest("item");

        // 构建基本查询
        buildBasicQuery(params,searchRequest);

        // 分页查询
        Integer page = params.getPage(); // 当前页码
        Integer size = params.getSize(); // 每页显示的数据量
        searchRequest.source().from((page - 1) * size);
        searchRequest.source().size(size);

        // 高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        searchRequest.source().highlighter(highlightBuilder);
        highlightBuilder.field("name");
        highlightBuilder.preTags("<em style='color:red'>");
        highlightBuilder.postTags("</em>");
        highlightBuilder.requireFieldMatch(false); // 高亮字段name与查询字段all不一致

        // 发起请求
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        return handleResponse(searchResponse);
    }

    private void buildBasicQuery(RequestParams params, SearchRequest searchRequest) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (StringUtils.isNotBlank(params.getKey())){
            // 根据输入的关键字查询
            boolQuery.must(QueryBuilders.matchQuery("all",params.getKey()));
        }else {
            // 没有输入关键字,查询全部
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        // 如果category不为空
        if (StringUtils.isNotBlank(params.getCategory())){
            // category查询时不分词,采取term查询
            boolQuery.filter(QueryBuilders.termQuery("category",params.getCategory()));
        }
        // 如果brand不为空
        if (StringUtils.isNotBlank(params.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }

        if (params.getMaxPrice() != null && params.getMinPrice() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice() * 100).lte(params.getMaxPrice() * 100));
        }

//        searchRequest.source().query(boolQuery);

        // 算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        searchRequest.source().query(functionScoreQuery);
    }

    private PageDTO<ItemDoc> handleResponse(SearchResponse searchResponse) {

        List<ItemDoc> itemList = new ArrayList<>();
        SearchHits searchHits = searchResponse.getHits();
        System.out.println("查询到的数据量为: " + searchHits.getTotalHits().value);

        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String jsonString = hit.getSourceAsString();
            // 将JSON字符串反序列化成对象
            ItemDoc itemDoc = JSON.parseObject(jsonString, ItemDoc.class);
            // 处理高亮的结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null) {
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null){
                    Text[] fragments = highlightField.fragments();
                    if (fragments != null && fragments.length > 0) {
                        String nameHighlight = fragments[0].toString(); // nameHighlight: "<span style='color:red'>如家</span>酒店(上海虹桥漕河泾古北店)"
                        itemDoc.setName(nameHighlight);
                    }
                }
            }
            itemList.add(itemDoc);
        }
        return new PageDTO<>(searchHits.getTotalHits().value, itemList);
    }


    @Override
    public Map filters(RequestParams requestParams) throws IOException {
        SearchRequest searchRequest = new SearchRequest("item");

        buildBasicQuery(requestParams,searchRequest);
        searchRequest.source().size(0);
        // 添加聚合条件
        searchRequest.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(20));
        searchRequest.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        Aggregations aggregations = searchResponse.getAggregations();

        List<String> categoryList = new ArrayList<>();
        Terms categoryTerms = aggregations.get("categoryAgg");
        List<? extends Terms.Bucket> categoryTermsBuckets = categoryTerms.getBuckets();
        for (Terms.Bucket categoryTermsBucket : categoryTermsBuckets) {
            categoryList.add(categoryTermsBucket.getKeyAsString());
        }

        List<String> brandList = new ArrayList<>();
        Terms brandTerms = aggregations.get("brandAgg");
        List<? extends Terms.Bucket> brandTermsBuckets = brandTerms.getBuckets();
        for (Terms.Bucket brandTermsBucket : brandTermsBuckets) {
            brandList.add(brandTermsBucket.getKeyAsString());
        }

        Map map = new HashMap();
        map.put("category",categoryList);
        map.put("brand",brandList);
        return map;
    }

    @Autowired
    private ItemClient itemClient;

    @Override
    public void itemUp(Long id) {
        // 查询商品信息
        Item item = itemClient.getById(id);
        // 将item对象转为itemDoc
        ItemDoc itemDoc = new ItemDoc(item);
        // 参考官网代码
        IndexRequest request = new IndexRequest("item"); // 对应ES索引库的名字
        request.id(id.toString());
        String jsonString = JSON.toJSONString(itemDoc);
        request.source(jsonString, XContentType.JSON);
        // 发起请求
        try {
            IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            log.info("商品上架后,ES中的数据同步成功");
        } catch (Exception e) {
            log.error("商品上架后,ES中的数据同步失败");
            e.printStackTrace();
        }
    }

    @Override
    public void itemDown(String itemIdString) {
        DeleteRequest deleteRequest = new DeleteRequest("item", itemIdString);
        try {
            restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
            log.info("商品下架后,ES中的数据同步成功");
        } catch (Exception e) {
            log.error("商品下架后,ES中的数据同步失败");
            e.printStackTrace();
        }
    }
}
